<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 https://www.meoyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 喵云科技 【https://www.meoyun.com】
// +----------------------------------------------------------------------


namespace app\admin\controller;

/**
 * 管理员用户控制器
 */

use app\common\model\Rule;
use app\common\service\BaseService;
use app\common\service\Utils;
use think\exception\ValidateException;
use think\facade\Request;
use think\facade\Db;
use app\common\model\Admin as AdminModel;
use app\common\model\User as UserModel;

class User extends AdminBase
{

    // 不需要权限验证的方法
    protected $middleware = [
        'app\admin\middleware\Auth' => ['except' => ['login','menuList']],
    ];

    //管理员登录
    public function login()
    {
        $data = Request::post(['username', 'password']);

        $user = AdminModel::where($data)->find();

        if ($user) {
            $update["id"] = $user->id;
            $update["login_ip"] = request()->ip();
            $update["last_login_time"] = time();

            AdminModel::update($update);

            $user["token"] = BaseService::buildToken(["userId" => $user->id]);
            return message($user, "登录成功");
        }

        return error("用户名或密码错误！");
    }

    //登录用户菜单权限
    public function menuList()
    {
        $userId = BaseService::getLoginUserId();

        $groupId = AdminModel::where("id", $userId)->value("group_id");

        $ruleIds = Db::name("group_rule")->where("group_id", $groupId)->column("rule_id");
        $userRule = Db::name("rule")->where("is_menu", 1)->where("id", "in", $ruleIds)->select();

        $treeRule = Utils::makeTree($userRule);

        return message($treeRule);
    }

    //删除用户
    public function delete()
    {
        $userIds = input("user_ids/a");

        $res = UserModel::destroy($userIds);

        if($res){
            return message('删除成功');
        }

        return error("删除失败");
    }

    //删除管理员
    public function delAdmin()
    {
        $userId = input("user_id");

        $res = AdminModel::where("id",$userId)->delete();

        if($res){
            return message('删除成功');
        }

        return error("删除失败");
    }

    //角色列表
    public function roleList()
    {
        $list = Db::name("group")->select();
        return message($list);
    }

    //管理员列表
    public function adminList()
    {
        $list = AdminModel::select()->each(function ($item) {
            $item["group_name"] = Db::name("group")->where("group_id", $item["group_id"])->value("name");
            return $item;
        });

        return message($list);
    }

    //保存管理员
    public function save()
    {
        $data = input("post.");
        $userId = input("id");

        try {
            validate(\app\common\validate\Admin::class)->check($data);
        } catch (ValidateException $e) {
            return error($e->getError());
        }

        if($userId){
            $user = AdminModel::update($data);
        }else{
            $user = AdminModel::create($data);
        }

        if ($user) {
            return message($user, "保存成功");
        }

        return error("保存失败");
    }

    //角色权限列表
    public function roleRuleList()
    {
        $id = input("id");

        $ruleUserIds = Db::name("group_rule")->where("group_id", $id)->column("rule_id");
        $ruleAll = Db::name("rule")->select()->each(function ($item, $key) use ($ruleUserIds) {
            if (in_array($item["id"], $ruleUserIds)) {
                $item["is_own"] = true;
            } else {
                $item["is_own"] = false;
            }

            return $item;
        });
        $treeRule["all_rule"] = Utils::makeTree($ruleAll);
        $treeRule["user_rule_ids"] = $ruleUserIds;
        return message($treeRule);
    }

    //保存角色权限
    public function ruleSave()
    {
        $ruleIds = input("rule_ids");
        $roleId = input("role_id");
        $data = [];

        foreach ($ruleIds as $id) {
            $data[] = ["group_id" => $roleId, "rule_id" => $id];
        }

        Db::name("group_rule")->where("group_id", $roleId)->delete();

        if (!empty($data)) {
            $res = Db::name("group_rule")->insertAll($data);
            if ($res) {
                return message("保存成功");
            }
            return error("保存失败");
        } else {
            return message("保存成功");
        }
    }

    //添加角色
    public function roleAdd()
    {
        $data = input("post.");
        $data["create_time"] = time();
        $res = Db::name("group")->insert($data);
        if ($res) {
            return message("添加成功");
        }

        return error("添加失败");
    }

    //删除角色
    public function roleDel()
    {
        $id = input("post.id");
        $res = Db::name("group")->where("group_id", $id)->delete();
        if ($res) {
            return message("删除成功");
        }

        return error("删除失败");
    }

    //权限规则列表
    public function ruleList()
    {
        $list = Db::name("rule")->paginate(10);
        return message($list);
    }

    //删除权限规则
    public function ruleDelete()
    {
        $userIds = input("rule_ids/a");

        $res = Rule::destroy($userIds);

        if($res){
            return message('删除成功');
        }

        return error("删除失败");
    }
}